package com.nullpointer.xchatfinal.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.nullpointer.xchatfinal.R;
import com.nullpointer.xchatfinal.adapter.UserAdapter;
import com.nullpointer.xchatfinal.object.User;
import com.nullpointer.xchatfinal.utils.Utils;
import com.quickblox.core.QBEntityCallbackImpl;
import com.quickblox.core.request.QBPagedRequestBuilder;
import com.quickblox.users.QBUsers;
import com.quickblox.users.model.QBUser;

public class SearchFriendDialogFragment extends DialogFragment {
	private EditText etSearch;
	private ListView lvUsers;
	private LinearLayout llInfo;
	private ProgressBar pbLoading;
	private TextView tvInfo;
	private Button btCancel;
	private ImageView ivSearch;

	private List<User> userData = new ArrayList<User>();
	private UserAdapter userAdapter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater
				.inflate(R.layout.fragment_search_friend, container);
		findViewIds(view);
		init();
		setEvent();
		return view;
	}

	private void init() {
		getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
		ivSearch.setEnabled(false);
		userAdapter = new UserAdapter(getActivity(), userData);
		lvUsers.setAdapter(userAdapter);
		hideInfo();
	}

	@Override
	public void onStart() {
		super.onStart();
		Dialog dialog = getDialog();
		if (dialog != null) {
			dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
					ViewGroup.LayoutParams.MATCH_PARENT);
			// dialog.getWindow().setBackgroundDrawable(
			// new ColorDrawable(Color.TRANSPARENT));

		}
	}

	private void setEvent() {
		btCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dismiss();
			}
		});

		ivSearch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				searchUser();
			}
		});

		etSearch.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (etSearch.getText().toString().trim().length() > 0) {
					ivSearch.setEnabled(true);
				} else {
					ivSearch.setEnabled(false);
				}
			}
		});

	}

	protected void searchUser() {
		userData.clear();
		userAdapter.notifyDataSetChanged();
		showSearchingInfo();
		String input = etSearch.getText().toString();
		QBPagedRequestBuilder pagedRequestBuilder = new QBPagedRequestBuilder();
		pagedRequestBuilder.setPage(1);
		pagedRequestBuilder.setPerPage(50);

		QBUsers.getUsersByFullName(input, pagedRequestBuilder,
				new QBEntityCallbackImpl<ArrayList<QBUser>>() {
					@Override
					public void onSuccess(ArrayList<QBUser> users, Bundle params) {
						for (QBUser qbUser : users) {
							userData.add(Utils.convertQBUserToUser(qbUser));
						}
						userAdapter.notifyDataSetChanged();
						searchByUserID();
					}

					@Override
					public void onError(List<String> errors) {
						searchByUserID();
					}
				});

	}

	private void searchByUserID() {
		String input = etSearch.getText().toString();
		Integer userID = 0;
		try {
			userID = Integer.parseInt(input);
		} catch (NumberFormatException e) {
			userID = 0;
		}
		if (userID == 0) {
			hideInfo();
			checkNotFound();
			return;
		}
		// not userid => not search
		QBUsers.getUser(userID, new QBEntityCallbackImpl<QBUser>() {
			@Override
			public void onSuccess(QBUser user, Bundle args) {
				userData.add(Utils.convertQBUserToUser(user));
				userAdapter.notifyDataSetChanged();
				checkNotFound();
			}

			@Override
			public void onError(List<String> errors) {
				checkNotFound();
			}
		});
	}

	private void checkNotFound() {
		if (userData.size() == 0) {
			showNoResultInfo();
		} else {
			hideInfo();
		}
	}

	private void showNoResultInfo() {
		showInfo("User " + etSearch.getText().toString() + " not found", false);
	}

	private void showSearchingInfo() {
		showInfo("Searching", true);
	}

	public void showInfo(String messgae, boolean isShowProgessbar) {
		llInfo.setVisibility(View.VISIBLE);
		tvInfo.setText(messgae);
		if (isShowProgessbar) {
			pbLoading.setVisibility(View.VISIBLE);
		} else {
			pbLoading.setVisibility(View.GONE);
		}
	}

	public void hideInfo() {
		llInfo.setVisibility(View.GONE);
	}

	private void findViewIds(View view) {
		etSearch = (EditText) view.findViewById(R.id.et_search);
		lvUsers = (ListView) view.findViewById(R.id.lv_user);
		llInfo = (LinearLayout) view.findViewById(R.id.ll_info);
		pbLoading = (ProgressBar) view.findViewById(R.id.pb_loading);
		tvInfo = (TextView) view.findViewById(R.id.tv_info);
		btCancel = (Button) view.findViewById(R.id.bt_cancel);
		ivSearch = (ImageView) view.findViewById(R.id.iv_search);
	}

}
